package service

import (
	"basic-go/syntax/webook/internal/repository"
	"basic-go/syntax/webook/internal/service/sms"
	"context"
	"fmt"
	"math/rand"
)

var (
	ErrCodeSendTooMany   = repository.ErrCodeSendTooMany
	ErrCodeVerifyTooMany = repository.ErrCodeVerifyTooMany
)

type CodeService interface {
	Send(ctx context.Context, biz, phone string) error
	Verify(ctx context.Context, biz, phone, inputcode string) (bool, error)
}

type codeService struct {
	cache repository.CodeRepository
	sms   sms.Service
}

func NewcodeService(cache repository.CodeRepository, sms sms.Service) CodeService {
	return &codeService{
		cache: cache,
		sms:   sms,
	}
}

func (c *codeService) Send(ctx context.Context, biz, phone string) error {
	// 发送验证码分三步：
	// 1 生成验证码
	code := c.generate()
	// 2 验证码存入redis
	err := c.cache.Set(ctx, biz, phone, code)
	if err != nil {
		return err
	}
	// 3 给手机发送验证码
	const codeTplId = "1877556"
	return c.sms.Send(ctx, codeTplId, []string{code}, phone)
	//return c.sms.

}

func (c *codeService) Verify(ctx context.Context, biz, phone, inputcode string) (bool, error) {
	return c.cache.Verify(ctx, biz, phone, inputcode)
}

func (c *codeService) generate() string {
	code := rand.Intn(1000000)
	return fmt.Sprintf("%06d", code)
}
